import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link, useHistory, useParams } from 'react-router-dom';
import styles from './index.module.scss';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

import { Channel } from '@/components/Channel';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import {
  publishArticleAction,
  getArticleDetailsAction,
} from '@/store/actions/publish';

const Publish = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  const { id } = useParams();
  const isEdit = id !== undefined;
  // 创建表单实例
  const [form] = Form.useForm();
  // 图片列表
  const [fileList, setFileList] = useState([]);

  // 上传图片数量
  const [maxCount, setMaxCount] = useState(1);

  // 存储图片仓库
  const imageList = useRef([]);

  // 编辑文章时去获取文章详情
  useEffect(() => {
    const loadData = async () => {
      if (isEdit) {
        const detail = await dispatch(getArticleDetailsAction(id));
        console.log(detail);
        const { cover, ...formValue } = detail;
        // 表单数据回填
        form.setFieldsValue({ ...formValue, type: cover.type });
        const newFileList = cover.images.map(item => ({ url: item }));

        // 回填图片列表数据
        setFileList(newFileList);
        setMaxCount(cover.type);
        imageList.current = newFileList;
      }
    };
    loadData();
  }, [dispatch, id, isEdit, form]);

  // 修改封面图片数量
  const changeType = e => {
    setMaxCount(e.target.value);
    switch (e.target.value) {
      case 0:
        setFileList([]);
        break;
      case 1:
        setFileList(imageList.current[0] ? [imageList.current[0]] : []);
        break;
      case 3:
        setFileList(imageList.current);
        break;
      default:
        break;
    }
  };
  // 上传图片的事件
  const onUploadImage = value => {
    const newFileList = value.fileList.map(file =>
      // 如果response没有数据，就说明图片还在上传中
      file.response ? { url: file.response.data.url } : file
    );
    // 存储上传的图片，方便切换展示
    imageList.current = newFileList;
    setFileList(newFileList);
  };

  // 上传文章
  const onFinish = value => {
    saveArticle(isEdit ? '文章编辑成功' : '文章上传成功', value, false);
  };
  // 上传草稿文件
  const saveDraft = async () => {
    try {
      const value = await form.validateFields();
      saveArticle('文章草稿保存成功', value, true);
    } catch (error) {}
  };

  // 保存文件 (提示信息， 请求参数， 是否是保存草稿)
  const saveArticle = async (msg, value, isDraft) => {
    const { type } = value;
    const images = fileList.map(item => item.url);
    if (images.some(item => item === undefined)) {
      return message.error('请等待图片上传完成');
    }
    if (type !== fileList.length) {
      return message.error('请按需上传图片');
    }
    const data = {
      ...value,
      cover: {
        type,
        images,
      },
    };
    if (isEdit) {
      data.id = id;
    }
    try {
      await dispatch(publishArticleAction(data, isDraft, isEdit));
      message.success(msg, 1, () => history.push('/home/article'));
    } catch (e) {}
  };
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{isEdit ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          // initialValues={details}
          onFinish={onFinish}
          // 表单实例和对应表单绑定
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel width={400}></Channel>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {maxCount !== 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                multiple={maxCount === 3}
                onChange={onUploadImage}
                fileList={fileList}
                action="http://geek.itheima.net/v1_0/upload"
                maxCount={maxCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {isEdit ? '编辑' : '发布'}文章
              </Button>
              <Button size="large" onClick={saveDraft}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
